package cn.tedu.jdbc;

import java.sql.*;
import java.util.Scanner;

/**使用预编译功能实现用户注册
 * 1.用户输入：用户名，密码，昵称，年龄；
 * 2.返回的结果：注册成功/用户名被占用
 * */
public class JDBCReg {
    public static void main(String[] args) {
        try(Connection connection = DBUtil.getConnection();) {
            Scanner scanner = new Scanner(System.in);
            System.out.println("用户名：");
            String username= scanner.nextLine();
            System.out.println("密码：");
            String password= scanner.nextLine();
            System.out.println("昵称：");
            String nickname= scanner.nextLine();
            System.out.println("年龄：");
            int age= scanner.nextInt();
            String sql="select id from userinfo where username=?And password=?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            ResultSet resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                System.out.println("用户名被占用");
            }else{
                String sql2="insert into userinfo(username,password,nickname,age)values(?,?,?,?)";
                PreparedStatement preparedStatement1 = connection.prepareStatement(sql2);
                preparedStatement1.setString(1,username);
                preparedStatement1.setString(2,password);
                preparedStatement1.setString(3,nickname);
                preparedStatement1.setInt(4,age);
                int i = preparedStatement1.executeUpdate();
                if(i==0){
                    System.out.println("注册失败");
                }else{
                    System.out.println("注册成功");
                }

            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
